<?php

declare (strict_types=1);

namespace app\cron\controller;

use app\service\base\FilesService;
use think\annotation\route\Group;
use app\cron\controller\Base;
use app\traits\UploadTrait;
use app\admin\middleware\CheckAdmin;
use think\facade\Env;
use think\annotation\Route;

/**
 * 文件上传
 * Class Upload
 * @package app\cron\controller;
 * @author  hardphp（2066362155@qq.com）
 * @Group("upload")
 *
 *
 */
class Upload extends Base
{
    use UploadTrait;

    /**
     * @Route("upfile", method="POST")
     */
    public function upfile()
    {
        $file = request()->file('file');
        if (empty($file)) {
            return json_error(10011);
        }
        try {
//            validate(['file' => 'fileSize:10485670|fileExt:pdf|fileMime:application/pdf'])->check(request()->file());
            $savename = \think\facade\Filesystem::putFile('files', $file);
            $savename = str_replace('\\', '/', $savename);
            $driver = Env::get('filesystem.driver', 'public');
            if($driver == 'aliyun') {
                $path     = config('filesystem.disks.aliyun.url') . '/' . $savename;
            } else if($driver == 'qcloud') {
                $path     = config('filesystem.disks.qcloud.cdn') . '/' . $savename;
            } else if($driver == 'qiniu') {
                $path     = config('filesystem.disks.qiniu.url') . '/' . $savename;
            } else {
                $path     = config('app.app_host').config('filesystem.disks.public.url') . '/' . $savename;
            }

            //保存数据库
            $res = FilesService::save([
                'hash'  => $file->hash('sha1'),
                'title' => $file->getOriginalName(),
                'mine' => $file->getOriginalMime(),
                'types' => 3,
                'size' => $file->getSize(),
                'url' => $path,
            ]);
            if (!$res) {
                return json_error(10012);
            }
            return json_ok(['path' => $path, 'id' => $res]);
        } catch (\think\exception\ValidateException $e) {
            return json_error($e->getMessage());
        }
    }
}
